// pages/order/order.js
var httpUtil = require('../../utils/httpUtil.js');
var util = require('../../utils/util.js');

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    flag: true,
    flag1: true,
    flag2: true,
    animationData: {},
    express: [{
        company: '免邮费',
        urlImg: '../images/sel-n.png',
        urlSelImg: '../images/apt.png',
        money: 0
      } 
    ],
    curIdx: 0,

    index:0,
    userInfo: {},
    address_money: 0,
    money: 0,
    moneyTotal: 0,
    goods: {},
    userAddress: {},
    address:{},
    specification: {},
    num: 1, remarks:"",
    goodsList:[],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var id = options.id;
     var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    var list=[];
    var moneyTotal = 0
    for (var i = 0; i < prevPage.data.shoppingList.length;i++){
      var data = prevPage.data.shoppingList[i];
      if (data.checked =='checked'){
        list.push(data);
        moneyTotal = parseFloat(moneyTotal) + parseFloat(data.moneyTotal)
      }
    }
    that.setData({
      goodsList: list,
      moneyTotal: moneyTotal
    })

    httpUtil.getHttp("/search/get/text"
      , { id: 6 }, function (res) {
        //将markdown内容转换为towxml数据
        let data = app.towxml.toJson(res.text, 'markdown');
        that.setData({
          text: data
        })
      })
  },
  
  getAddress: function(id) {
    var that = this;
    var userInfo = util.getKey("userInfo");

    httpUtil.getHttp("/user/address?userId=" + userInfo.id, {}, function(res) {
      that.setData({
        address: res,
        userInfo: userInfo
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getAddress();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  costShow: function(e) {
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 500,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(200).step()
    // 用setData改变当前动画

    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      flag: !that.data.flag
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function() {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  costHide: function(e) {
    var that = this;
    that.setData({
      flag: true
    })
  },
  selExpress: function(e) {
    var that = this;
    var model = that.data.goodsList[that.data.index];
    var moneyTotal = 0;

    model.curIdx=e.currentTarget.dataset.index;
    model.moneyTotal = (model.money * model.goodsCar.num) + parseFloat(model.logisticsModelList[model.curIdx].money) + parseFloat(model.insuranceMoney);

    that.data.goodsList[that.data.index] = model;
    that.setData({
       goodsList: that.data.goodsList,
      flag1: true
    })
    for (var i = 0; i < that.data.goodsList.length; i++) {
      var data = that.data.goodsList[i];
          moneyTotal = parseFloat(moneyTotal) + parseFloat(data.moneyTotal)
     }
    that.setData({
       moneyTotal: moneyTotal
    })

  },
  selPurchase: function(e) {
    // 用that取代this，防止不必要的情况发生
    var that = this;
    var index = e.target.dataset.index;
    console.log(index);
    this.setData({
       express: that.data.goodsList[index].logisticsModelList,
      index: index,
      curIdx: that.data.goodsList[index].curIdx
    })

    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 500,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(200).step()
    // 用setData改变当前动画

    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      flag1: false
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function() {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  hidePurchase: function() {
    var that = this;
    that.setData({
      flag1: true
    })
  },
  getAddressList: function() {
    wx.navigateTo({
      url: '../addressList/addressList'
    })
  },
  add: function(e) {
 
    var that = this;
    var index = e.target.dataset.index;
    var model = that.data.goodsList[index];
    if (model.goodsCar.num > 0) {
      model.goodsCar.num = model.goodsCar.num + 1;
      model.moneyTotal = parseFloat(((model.money * model.goodsCar.num) + parseFloat(model.logisticsModelList[model.curIdx].money) + parseFloat(model.insuranceMoney)).toFixed(2));
      that.setData({
        goodsList: that.data.goodsList
      })
      httpUtil.getHttp("/car/add/num?id=" + model.goodsCar.id, {}, function (res) {
 
      })
     
    }
    var moneyTotal = 0;

    for (var i = 0; i < that.data.goodsList.length; i++) {
      var data = that.data.goodsList[i];
      moneyTotal = parseFloat((parseFloat(moneyTotal) + parseFloat(data.moneyTotal)).toFixed(2))
    }

    that.setData({
      moneyTotal: moneyTotal
    })
  },
  del: function(e) {
    var that = this;
    var index = e.target.dataset.index;
    var model = that.data.goodsList[index];
    if (model.goodsCar.num > 1) {
      model.goodsCar.num = model.goodsCar.num - 1;
      model.moneyTotal = parseFloat(((model.money * model.goodsCar.num) + parseFloat(model.logisticsModelList[model.curIdx].money) + parseFloat(model.insuranceMoney)).toFixed(2));
      that.setData({
        goodsList: that.data.goodsList
      })
      httpUtil.getHttp("/car/del/num?id=" + model.goodsCar.id, {}, function (res) {
    
          
      })
    }
    var moneyTotal = 0;

    for (var i = 0; i < that.data.goodsList.length; i++) {
      var data = that.data.goodsList[i];
      moneyTotal = parseFloat((parseFloat(moneyTotal) + parseFloat(data.moneyTotal)).toFixed(2))
    }
    that.setData({
      moneyTotal: moneyTotal
    })

  },
  address_money: function(e) {
    var that = this;
    var index = e.target.dataset.index;
    var model = that.data.goodsList[index];
    var moneyTotal=0;
      model.insuranceMoney=(model.insuranceMoney == 0 ? parseFloat(model.freightInsuranceMoney) : 0);
    model.moneyTotal = (model.money * model.goodsCar.num) + parseFloat(model.logisticsModelList[model.curIdx].money) + parseFloat(model.insuranceMoney);
    that.data.goodsList[index]=model;
    that.setData({
      goodsList: that.data.goodsList
    })
    for (var i = 0; i < that.data.goodsList.length; i++) {
      var data = that.data.goodsList[i];
      moneyTotal = parseFloat(moneyTotal) + parseFloat(data.moneyTotal)
    }
    that.setData({
      moneyTotal: moneyTotal
    })
  }, remarks: function (e) {
    var that = this; 
    var value = e.detail.value;
    var index = e.target.dataset.index;
    that.data.goodsList[index].remarks = value;
    that.setData({
      goodsList: that.data.goodsList
    })
  }, 

  
  pay: function() {
    var that = this;
    var address = that.data.address;

    if (address == '' || address.id == null) {
      wx.showToast({
        title: '请填写地址',
        icon: 'succes',
        duration: 1000,
        mask: true
      })
      return;
    }
    
    var userInfo = util.getKey("userInfo");

    httpUtil.postHttp("/order/pay/goods/car?userId=" + userInfo.id  
      , { address: address,list:that.data.goodsList}, function(res) {
      wx.requestPayment({
        'timeStamp': res.data.timeStamp,
        'nonceStr': res.data.nonceStr,
        'package': res.data.package,
        'signType': res.data.signType,
        'paySign': res.data.paySign,
        'success': function(res) {
          wx.showToast({
            title: "支付成功",
            icon: 'loading',
            duration: 500
          });
          wx.navigateTo({
            url: '../paySuccess/paySuccess'
          })
        },
        'fail': function(res) {
          console.log(res);
          wx.showToast({
            title: "支付失败",
            icon: 'loading',
            duration: 500
          });

        }
      })
    })


  },
  yfTipcont:function(){
    var that=this;

    this.setData({
      flag2: false
     })
  },
  hideyf:function(){
    this.setData({
      flag2: true
    })
  }, //用户选择收货地址
  chooseAddress: function () {
    var that = this;
    if (wx.chooseAddress && that.data.userAddress == '') {
      wx.chooseAddress({
        success: function (res) {
          console.log(JSON.stringify(res));
          console.log(res);
          that.setData({
            userAddress: res.provinceName + res.cityName + res.countyName + res.detailInfo,
            userName: res.userName,
            userPhone: res.telNumber
          })

        },
        fail: function (err) {
          console.log(JSON.stringify(err));
          console.info("收货地址授权失败");
          wx.showToast({
            title: '授权失败，您将无法进行下单支付;重新授权请删除小程序后再次进入',
            icon: 'success',
            duration: 20000
          })
        }
      })
    } else {
      console.log('当前微信版本不支持chooseAddress');
    }
  },
   //用户选择收货地址
  chooseAddress: function () {
    var that = this;
     if (wx.chooseAddress &&( that.data.address == '' || that.data.address=={})) {
      wx.chooseAddress({
        success: function (res) {
          console.log(JSON.stringify(res));
          console.log(res);
          var userInfo = util.getKey("userInfo");

          var address = { "name": res.userName, "phone": res.telNumber, "province": res.provinceName, "city": res.cityName, "area": res.countyName, "text": res.detailInfo, "userId": userInfo.id}
       
          httpUtil.postHttp("/user/address/save", address, function (res) {
            that.setData({
              address: address
            })
          })
        },
        fail: function (err) {
          console.log(JSON.stringify(err));
          console.info("收货地址授权失败");
          wx.showToast({
            title: '授权失败，您将无法进行下单支付;重新授权请删除小程序后再次进入',
            icon: 'success',
            duration: 20000
          })
        }
      })
    } else {
      console.log('当前微信版本不支持chooseAddress');
      that.getAddressList();
    }
  },
})